package com.wwz.leetcode;

import com.wwz.common.TreeNode;
import org.junit.Test;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * @description: 二叉树的层序遍历
 * @author: Sailor
 * @date: 2023-12-17 11:43:04
 */

public class LeetCode102 {

    @Test
    public void test(){
        levelOrder(new TreeNode(3,new TreeNode(9,null,null),new TreeNode(20,new TreeNode(15,null,null),new TreeNode(7,null,null))));
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> resList = new ArrayList<>();

        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            int n = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    // 将左子树放入队列
                    queue.add(node.left);
                }
                if (node.right != null) {
                    // 将右子树放入队列
                    queue.add(node.right);
                }
            }
            resList.add(level);
        }
        return resList;
    }
}

